package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    //调用支付宝生成二维码
    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String submit(@PathVariable Long orderId) {
        return alipayService.submit(orderId);
    }

    //同步回调
    @GetMapping("/callback/return")
    public String callback() {
        System.out.println("支付宝同步回调，跳转支付成功页面");
        return "redirect:" + AlipayConfig.return_order_url;
    }

    //异步回调
    @PostMapping("/callback/notify")
    public String notify(@RequestParam Map<String, String> paramsMap) {
        System.out.println("异步通知");
        try {
            //确认是否是支付宝发来的
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    paramsMap, AlipayConfig.alipay_public_key,
                    AlipayConfig.charset, AlipayConfig.sign_type);
            if (signVerified) {
                System.out.println(paramsMap);
                //获取支付宝发来的状态
                String tradeStatus = paramsMap.get("trade_status");
                //获取并判断支付发来的订单状态
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    //---1:金额也是正确的
                    //2:更新支付信息表  银行流水  时间  内容
                    //3:更新订单状态 未支付改为已支付
                    //-- 4:本项目没有使用  用户收到一优惠
                    //5:订单商品库存 扣减商品剩余库存
                    //.........  用户级别  用户积分
                    paymentInfoService.paySuccess(paramsMap);
                    //返回支付宝确认状态
                } else {
                    //支付宝状态出错
                    return "failure";
                }
            } else {
                //TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }

    //退款
    @GetMapping("/refund/{outTradeNo}")
    @ResponseBody
    public Result refund(@PathVariable String outTradeNo){

        alipayService.refund(outTradeNo);

        return Result.ok();
    }
}